      SUBROUTINE HAG
C
C     HAG CALCULATES THE FLUX DENSITY OF THE EARTH'S MAGNETIC
C     FIELD IN LOCAL INERTIAL COORDINATES
C
      IMPLICIT REAL*8 (A-H,O-Z)
      REAL*8 J2,J3,J4,J22
C
      COMMON/CNBODY/ J2,J3,J4,J22,ZJ20,ZMU,WWO,FLAT,AEARTH
C
      COMMON/CONSTS/ PI,TWOPI,RADIAN
C
      COMMON/DEBUG2/ IOUT,JOUT,KLUGE
C
      COMMON/RPOOL1/ RHOK(10),TIME,SA(3,3),FM1(3,3),ZLK(10),OMEG(3),
     *               ZLKP(10),ZLKDP(10),CMAT(3,3),GBAR(3,3),YBCM(3),
     *               ZBZK(3,10),FCM(3,3),DTO,PHID,PHI1
C
      COMMON/RMGNTC/ SMAGI(3),DPMAG(3),SFMAG,MAGFLD
C
      COMMON/SUBPOS/ ALAT,ALONG,HGT
C
      COMMON/VECTRS/ XSAT(3),XSATDT(3),AD(3)
C  COMMON IDATE1 IS USED TO COMPUTE TM FOR ALLMAG INPUT
      COMMON/IDATE1/IY,IM,IDAY
C
C                       CALCULATE  EARTH-FIXED X,Y,Z COORDINATES
C                       AND LATITUDE(GEODETIC),LONGITUDE AND HEIGHT
C
C
      CALL XYZPLH(XSAT)
C
C                        LONGITUDE WITH RESPECT TO THE VERNAL
C                        EQUINOX
C
      WT=DATAN2(XSAT(2),XSAT(1))
C   COMPUTE DAYS INTO DECIMAL YEARS AND CONVERT IT INTO THE
C   FLOATING VARIABLE
      DEN=365.0D0
      IF(MOD(IY,4).EQ.0) DEN=366.0D0
      DAY=TIME/86400.D0
      TM=1900.0D0+IY+DAY/DEN
C   AT THIS POINT, SET MODEL=5
      MODEL=MAGFLD
      GDLAT=ALAT/RADIAN
      GDLON=ALONG/RADIAN
      ALT=HGT
      IF(IOUT.NE.1) WRITE(6,1000) MODEL,TM,GDLAT,GDLON,ALT
 1000 FORMAT('0',5X,'IOUT FROM HAG',I3,1P4E14.6)
      CALL GDALMG(MODEL,TM,GDLAT,GDLON,ALT,X,Y,Z,F,H,DEC,AINC)
      IF(IOUT.NE.1) WRITE(6,1000) MODEL,WT,X,Y,Z
C   TRANGFORM INTO INERTIAL(EQUATORIAL) COORDINATE
      STH=DSIN(WT)
      CTH=DCOS(WT)
      SPH=DSIN(ALAT)
      CPH=DCOS(ALAT)
C
      A1=CPH*CTH
      A2=-STH
      A3=-SPH*CTH
C
      B1=CPH*STH
      B2=CTH
      B3=-SPH*STH
C
      C1=SPH
      C2=0.0D0
      C3=CPH
C   COMPUTE THE MAGNETIC FIELD VECTOR IN INERTIAL FRAME
      BN=X
      BE=Y
      BV=Z
      SMAGI(1)=A1*BV+A2*BE+A3*BN
      SMAGI(2)=B1*BV+B2*BE+B3*BN
      SMAGI(3)=C1*BV+C2*BE+C3*BN
C
C
      RETURN
      END
